package com.ruoyi.system.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ITaskOneService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/system/one")
public class TaskOneController extends BaseController
{
    @Autowired
    private ITaskOneService taskOneService;

    @Autowired
    private TaskOneMapper taskOneMapper;

    @Autowired
    private TaskTwoMapper taskTwoMapper;

    @Autowired
    private TaskThreeMapper taskThreeMapper;

    @Autowired
    private TaskFourMapper taskFourMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Value("${ruoyi.profile}")
    private String profile;

    private static final Logger log = LoggerFactory.getLogger(TaskOneController.class);

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:one:list')")
    @GetMapping("/list")
    public TableDataInfo list(TaskOne taskOne)
    {

        //查询自己的数据根据角色
        LoginUser loginUser = SecurityUtils.getLoginUser();
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("role_id")
                .eq("user_id", loginUser.getUserId());
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(queryWrapper);
        List<Long> roleIdList = new ArrayList<>();
        sysUserRoles.stream().forEach(roleId -> {
            roleIdList.add(roleId.getRoleId());
        });
        //根据角色id
        if (roleIdList.contains(100L)) {
            taskOne.setFollowPerson(loginUser.getUser().getNickName());
        }


        if (com.ruoyi.common.utils.StringUtils.isNotEmpty(taskOne.getJudgmentStatus())){
            switch (taskOne.getJudgmentStatus()){
                case "0":
                    taskOne.setJudgmentStatus("Excel");
                    break;
                case "1":
                    taskOne.setJudgmentStatus("Xmind");
                    break;
                case "2":
                    taskOne.setJudgmentStatus("Word");
                    break;
            }
        }
        List<TaskOne> list;


        if (com.ruoyi.common.utils.StringUtils.isEmpty(taskOne.getKeyWordByList())){
            startPage();
            list = taskOneService.selectTaskOneList(taskOne);
            return getDataTable(list);
        }else {
            startPage();
            list = taskOneService.selectTaskOneListByKeyWord(taskOne);
            return getDataTable(list);
        }


    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:one:export')")
//    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TaskOne taskOne)
    {
        List<TaskOne> list = taskOneService.selectTaskOneList(taskOne);
        ExcelUtil<TaskOne> util = new ExcelUtil<TaskOne>(TaskOne.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:one:query')")
    @Log(title = "一号表详情", businessType = BusinessType.DETAIL, tableIndex = 1)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(taskOneService.selectTaskOneById(id));
    }

    /**
     * 新增【】
     * tableType = 1   类型(0.操作行为 1.操作日志)
     */
    @PreAuthorize("@ss.hasPermi('system:one:add')")
    @Log(title = "一号表新增", businessType = BusinessType.INSERT, tableIndex = 1,isAnalysisJson = true)
    @PostMapping
    public AjaxResult add(@RequestBody TaskOne taskOne)
    {

        if (taskOne.getId() != null){
            QueryWrapper<TaskOne> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id").eq("id",taskOne.getId());
            TaskOne taskOneIsExit = taskOneMapper.selectOne(queryWrapper);
            if(taskOneIsExit != null){
                return AjaxResult.error("当前任务中心编号已存在");
            }
        }


        taskOneService.insertTaskOne(taskOne);
        TaskLogOne taskLogOne = new TaskLogOne();
        taskLogOne.setTaskId(taskOne.getId());
        taskLogOne.setContent(taskOne.getContent());

        return AjaxResult.success("200",taskLogOne);
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:one:edit')")
    @Log(title = "一号表修改", businessType = BusinessType.UPDATE, tableIndex = 1)
    @PutMapping
    public AjaxResult edit(@RequestBody TaskOne taskOne)
    {

        //修改的新id不为空
        if (taskOne.getNewId() != null){
            QueryWrapper<TaskOne> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("id").eq("id",taskOne.getNewId());
            TaskOne taskOneIsExit = taskOneMapper.selectOne(queryWrapper);
            if(taskOneIsExit != null){
                return AjaxResult.error("当前任务中心编号已存在");
            }
        }

        taskOneService.updateTaskOne(taskOne);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id", taskOne.getId());
        map.put("content", taskOne.getContent());
        return AjaxResult.success("操作成功",map);
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:one:remove')")
    @Log(title = "一号表删除", businessType = BusinessType.DELETE, tableIndex = 1)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {

        taskOneService.deleteTaskOneByIds(ids);
        String id = Arrays.toString(ids).replace("[", "").replace("]", "");
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id",  id);
        return AjaxResult.success("操作成功",map);
    }


    /**
     * 全量搜索 （四表合起来）
     */
    @PostMapping("/batchSelect")
    public AjaxResult taskLogList(@RequestBody TaskOne taskOne){

        List<BatchTaskList> batchTaskOneList = new ArrayList<>();

        List<BatchTaskList> batchTaskTowList = new ArrayList<>();

        List<BatchTaskList> batchTaskThreeList = new ArrayList<>();

        List<BatchTaskList> batchTaskFourList = new ArrayList<>();

        //表一查询
        List<TaskOne> taskOneList = taskOneMapper.selectListByKeyWord(taskOne.getKeyword());
        if (CollectionUtils.isNotEmpty(taskOneList)){
            taskOneList.forEach(value ->{
                BatchTaskList batchTaskOne = new BatchTaskList();
                StringBuilder stringBuilder = new StringBuilder();

                if (value.getCaseIntroduction() !=null && value.getCaseIntroduction().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("案件介绍;");
                }
                if (value.getLocationHideout() !=null && value.getLocationHideout().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("窝点大致位置;");
                }
                if (value.getControlledBriefing() !=null && value.getControlledBriefing().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("被控人基本情况简介;");
                }
                if (value.getConfig() !=null && value.getConfig().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("新增配置-自定义内容;");
                }
                if (value.getContent() !=null && value.getContent().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("进度汇报内容;");
                }

                batchTaskOne.setFieldNumber(value.getFieldNumber());
                batchTaskOne.setFileds(stringBuilder);
                batchTaskOne.setId(value.getId());
                batchTaskOne.setTaskName("主任务");
                batchTaskOneList.add(batchTaskOne);
            });
        }


        //表二查询
        List<TaskTwo> taskTwoList = taskTwoMapper.selectListByKeyWord(taskOne.getKeyword());
        if(CollectionUtils.isNotEmpty(taskTwoList)){
            taskTwoList.forEach(value ->{
                BatchTaskList batchTaskOne = new BatchTaskList();
                StringBuilder stringBuilder = new StringBuilder();

                if (value.getOther() !=null && value.getOther().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("其它;");
                }

                if (value.getKeyClues() !=null && value.getKeyClues().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("虚转实关键线索;");
                }

                if (value.getPersonRelationship() !=null && value.getPersonRelationship().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("人物关系关联;");
                }

                if (value.getRemarks() !=null && value.getRemarks().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("备注;");
                }

                batchTaskOne.setFieldNumber(value.getFieldNumber());
                batchTaskOne.setFileds(stringBuilder);
                batchTaskOne.setId(value.getId());
                batchTaskOne.setTaskId(value.getTaskId());
                batchTaskOne.setTaskName("关键信息");
                batchTaskTowList.add(batchTaskOne);
            });
        }

        //表三查询
        List<TaskThree> taskThreeList = taskThreeMapper.selectListByKeyWord(taskOne.getKeyword());
        if(CollectionUtils.isNotEmpty(taskThreeList)){
            taskThreeList.forEach(value ->{
                BatchTaskList batchTaskOne = new BatchTaskList();
                StringBuilder stringBuilder = new StringBuilder();

                if (value.getBindInfo() !=null && value.getBindInfo().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("绑定信息;");
                }

                if (value.getAddress() !=null && value.getAddress().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("地址;");
                }

                batchTaskOne.setFieldNumber(value.getFieldNumber());
                batchTaskOne.setFileds(stringBuilder);
                batchTaskOne.setId(value.getId());
                batchTaskOne.setTaskId(value.getTaskId());
                batchTaskOne.setTaskName("账号密码类");
                batchTaskThreeList.add(batchTaskOne);
            });
        }

        //表四查询
        List<TaskFour> taskFourList = taskFourMapper.selectListByKeyWord(taskOne.getKeyword());
        if (CollectionUtils.isNotEmpty(taskFourList)){
            taskFourList.forEach(value ->{
                BatchTaskList batchTaskOne = new BatchTaskList();
                StringBuilder stringBuilder = new StringBuilder();

                if (value.getRemarks() !=null && value.getRemarks().contains(taskOne.getKeyword())){
                    value.setFieldNumber(value.getFieldNumber()+1);
                    stringBuilder.append("备注;");
                }


                batchTaskOne.setFieldNumber(value.getFieldNumber());
                batchTaskOne.setFileds(stringBuilder);
                batchTaskOne.setId(value.getId());
                batchTaskOne.setTaskId(value.getTaskId());
                batchTaskOne.setTaskName("IM");
                batchTaskFourList.add(batchTaskOne);

            });

        }

        BatchList batchList = new BatchList();
        batchList.setTaskOneList(batchTaskOneList);
        batchList.setTaskTwoList(batchTaskTowList);
        batchList.setTaskThreeList(batchTaskThreeList);
        batchList.setTaskFourList(batchTaskFourList);

        return AjaxResult.success(batchList);
    }




    //文件上传，仅限excel、word、xmind
    @PostMapping("upload")
    public AjaxResult upload(MultipartFile file)
    {

        log.info("文件路径{}",profile);
        try
        {
            String fileSuffix = StringUtils.getFilenameExtension(StringUtils.cleanPath(file.getOriginalFilename()));

            log.info("文件后缀{}",fileSuffix);
            if (fileSuffix.equals("doc")  || fileSuffix.equals("xls") || fileSuffix.equals("xlsx") || fileSuffix.equals("xmind") || fileSuffix.equals("docx")){
                // 上传并返回访问地址
                String uploadUrl = FileUploadUtils.upload(profile, file, new String[]{fileSuffix});
                return AjaxResult.success(fileSuffix,uploadUrl);
            }else {
                return AjaxResult.error("文件格式不正确");
            }
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }



    /**
     * 查询子任务编号
     */
    @PreAuthorize("@ss.hasPermi('system:one:list')")
    @GetMapping("/subList")
    public AjaxResult subList()
    {
        QueryWrapper<TaskOne> queryWrapper =  new QueryWrapper<>();
        queryWrapper.select("id");


        List<TaskOne> taskOneList = taskOneMapper.selectList(queryWrapper);
        return AjaxResult.success("子任务列表查询成功",taskOneList);

    }


    //word导出
    public static void main(String[] args) throws IOException, InterruptedException {

        XWPFDocument doc = new XWPFDocument();

        XWPFParagraph paragraph = doc.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Hello");


        FileOutputStream out = new FileOutputStream("output.docx");
        doc.write(out);
        out.close();
        Process process = Runtime.getRuntime().exec(" attrib +r output.docx");
        process.waitFor();


        //linux
        //output.docx  文件名
//        try {
//            Process process = Runtime.getRuntime().exec("chmod 444" + "output.docx");
//            process.waitFor(); // 等待进程完成
//        } catch (IOException | InterruptedException e) {
//            e.printStackTrace();
//        }

    }












}
